using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using System.Text;
using System.Web;
using System.Collections;
using System.IO;
using System.DirectoryServices;

public partial class ApplicationDataEntry : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        if (ViewState["view"] != null)
        {
            SetTabActive(ViewState["view"].ToString());
        }
        else
        {
            ViewState["view"] = "new";
            SetTabActive(ViewState["view"].ToString());
        }

        if (Session["finishAdd"] != null)
        {
            Session["finishAdd"] = null;
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "Application added sucessfully", "errorkey");
        }


        int intAppID = 0;
        bool idExist = Int32.TryParse(Request.QueryString["ID"], out intAppID);
        string action = Request.QueryString["action"];

        if (!Page.IsPostBack)
        {
            //Load Drop Down List Information
            LoadOrganizationDDL();
            LoadContactTypeDDL();
            LoadPropertyDDL();
            LoadPropertyListBox();

            if (action == "add")
            {
                SetNew();
                SetAddApplicationActive();
                if (idExist)
                {
                    txtApplicationID.Text = intAppID.ToString();
                    FillAppInfo(intAppID, true);
                }
            }
            else if (action == "edit")
            {
                SetEdit();
                if (idExist)
                    FillEditData(intAppID);
                else
                    SetEditApplicationActive();
            }
            else
            {
                SetNew();
                SetAddApplicationActive();
            }
        }
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    private void ValidateUserContact(int intAppid, string strUserAlias)
    {
        if (ConfigurationManager.AppSettings["RestictUpdatesToContacts"].ToString().ToUpper() == "TRUE")
        {
            int qty = WTRIAssessmentBL.RestictUpdatesToContacts(intAppid, Session["loginname"].ToString());
            if (qty == 0)
            {
                pnlError.Visible = true;
                btnUpdate.Visible = false;
                btnReset.Text = "Cancel";
                btnAdd.Enabled = false;
                pnlAppMetaData.Enabled = false;
                btnFindUser.Enabled = false;
                gridApplicationContact.Columns[0].Visible = false;
            }
            else
            {
                pnlError.Visible = false;
                btnUpdate.Visible = true;
                btnReset.Text = "Cancel";
                btnAdd.Enabled = true;
                pnlAppMetaData.Enabled = true;
                btnFindUser.Enabled = true;
                gridApplicationContact.Columns[0].Visible = true;
            }
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Validate("app");
        Validate("edit");
        if (Page.IsValid)
        {
            try
            {
                ApplicationCDE appData = LoadAppDatafromForm();
                appData.ModifiedBy = Session["loginname"].ToString();
                appData.ApplicationID = Int32.Parse(txtAppID.Text);
                string attributes = ExtractAttributeGuids();
                string strContactXML = ParseContactsXML();

                ApplicationsBL.UpdateApplication(appData, attributes, ParseContactsXML());

                if (Request.QueryString["ID"] == null)
                {
                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "Application updated sucessfully", "errorkey");
                    pnlApplication.Visible = false;
                    pnlSearch.Visible = true;
                    lstApplicationNames.Visible = false;
                    lblResult.Visible = false;
                    btnGo.Visible = false;
                    txtSearch.Text = null;
                    rdsearchType.SelectedValue = "0";
                }
                else
                {
                    Session["appUpd"] = "true";
                    int id = Int32.Parse(Request.QueryString["id"]);
                    Response.Redirect("~/Application/ApplicationDataEntryView.aspx?ID=" + id);
                }
            }
            catch (Exception ex)
            {
                string strErrorType = ex.Message.ToString().Substring(0, 8);

                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                if (!Request.IsLocal && strErrorType != "APMError")
                {
                    Server.ClearError();
                    Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                }
            }
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    protected void btnGo_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            int intAppID = Int32.Parse(this.lstApplicationNames.SelectedItem.Value);
            FillEditData(intAppID);
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
            this.btnUpdate.Visible = false;
        }
    }

    private void FillEditData(int appID)
    {
        pnlApplication.Visible = true;
        pnlError.Visible = false;
        pnlCopy.Visible = false;
        pnlApplicationID.Visible = true;
        pnlCompletedDate.Visible = true;
        pnlAppPropertyAdd.Visible = true;
        pnlAppContact.Visible = true;
        pnlContactError.Visible = false;

        pnlSearch.Visible = false;

        btnSubmit.Visible = false;
        btnUpdate.Visible = true;
        btnReset.Visible = true;
        btnReset.Text = "Cancel";

        if (ddlInsertContactType.Items.Count == 1)
            btnAdd.Enabled = false;
        else
            btnAdd.Enabled = true;

        FillAppInfo(appID, false);
        ValidateUserContact(appID, Session["loginname"].ToString());
    }

    protected void Search(string name, int id)
    {
        try
        {
            ArrayList list = ApplicationsBL.GetSearchApplicationData(name, id);

            lstApplicationNames.Items.Clear();
            foreach (ListItem lstTemp in list)
            {
                lstApplicationNames.Items.Add(lstTemp);
            }

            lstApplicationNames.Visible = true;
            lblResult.Visible = true;
            btnGo.Visible = true;
        }
        catch (Exception ex)
        {
            string strErrorType = ex.Message.ToString().Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
            }
            btnGo.Visible = false;
            lstApplicationNames.Visible = false;
            lblResult.Visible = false;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //Try to parse the search parameter if it can be converted to Integer value
            int searchByID;
            int intSearchType = Int32.Parse(rdsearchType.SelectedValue.ToString());

            bool IDFound = Int32.TryParse(txtSearch.Text, out searchByID);
            if (intSearchType == 1)
            {
                try
                {
                    if (IDFound)// Search parameter is an Integer value so search will be either on application name or application id
                        Search(txtSearch.Text, searchByID);
                    else
                        throw new Exception("APMError021");
                }
                catch (Exception ex)
                {
                    string strErrorType = ex.Message.ToString().Substring(0, 8);

                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                    if (!Request.IsLocal && strErrorType != "APMError")
                    {
                        Server.ClearError();
                        Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                    }
                }
            }
            else
            {
                //Search parameter is a string so search will be on application name
                Search(txtSearch.Text, 0);
            }
        }
        else
        {
            string msg = "Please correct the following:\\n- Required Field: Application Name/ID";
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg, "errorkey");
        }
    }

    private void SetNew()
    {
        ViewState["view"] = "new";
        editl.Attributes.Remove("class");
        viewl.Attributes.Remove("class");
        addl.Attributes.Add("class", "active");
    }

    protected void lbview_Click(object sender, EventArgs e)
    {
        Session["search"] = null;
        Response.Redirect("~/Application/ApplicationDataEntryView.aspx");
    }

    private void SetEdit()
    {
        ViewState["view"] = "edit";
        viewl.Attributes.Remove("class");
        addl.Attributes.Remove("class");
        editl.Attributes.Add("class", "active");
    }

    protected void lbedit_Click(object sender, EventArgs e)
    {
        Session["search"] = null;
        Response.Redirect("~/Application/ApplicationDataEntry.aspx?action=edit");
    }

    private string ParseContactsXML()
    {
        List<ApplicationContactCDE> list = (List<ApplicationContactCDE>)ViewState["contactlist"];
        foreach (ApplicationContactCDE contact in list)
        {
            if (!contact.Active)
            {
                throw new Exception("APMError031");
            }
        }

        DataSet dsXML = new DataSet("ContactList");
        dsXML.Tables.Add(dtContactTypes());

        System.IO.MemoryStream contactsListXML = new System.IO.MemoryStream();
        dsXML.WriteXml(contactsListXML, XmlWriteMode.IgnoreSchema);
        contactsListXML.Position = 0;
        StreamReader xmlStream = new StreamReader(contactsListXML);
        string strXML = xmlStream.ReadToEnd().ToString();
        strXML = strXML.Replace("T00:00:00-0[0-9]:00", "");
        xmlStream.Dispose();
        return strXML;
    }

    private DataTable dtContactTypes()
    {
        DataTable dt = new DataTable("Contacts");
        DataColumn[] column = new DataColumn[4];
        column[0] = new DataColumn("ContactName", System.Type.GetType("System.String"));
        dt.Columns.Add(column[0]);
        column[1] = new DataColumn("ContactTypeID", System.Type.GetType("System.String"));
        dt.Columns.Add(column[1]);
        column[2] = new DataColumn("ContactEmail", System.Type.GetType("System.String"));
        dt.Columns.Add(column[2]);
        column[3] = new DataColumn("ContactAlias", System.Type.GetType("System.String"));
        dt.Columns.Add(column[3]);

        List<ApplicationContactCDE> contactList = (List<ApplicationContactCDE>)ViewState["contactlist"];
        DataRow[] dr = new DataRow[contactList.Count + 1];

        int cnt = 0;
        foreach (ApplicationContactCDE contact in contactList)
        {
            dr[cnt] = dt.NewRow();
            dr[cnt]["ContactName"] = contact.Name;
            dr[cnt]["ContactTypeID"] = contact.ContactTypeID;
            dr[cnt]["ContactEmail"] = contact.Email;
            dr[cnt]["ContactAlias"] = contact.Alias;
            dt.Rows.Add(dr[cnt]);

            cnt++;
        }

        //Application Owner
        UserCDE loggedUser = UsersBL.GetUserByUserAlias(Session["loginname"].ToString());
        dr[cnt] = dt.NewRow();
        dr[cnt]["ContactName"] = loggedUser.UserName;
        dr[cnt]["ContactTypeID"] = "99998b54-da83-4d1a-858c-43a377b86c9e";
        dr[cnt]["ContactEmail"] = loggedUser.UserEmail;
        dr[cnt]["ContactAlias"] = loggedUser.UserAlias;
        dt.Rows.Add(dr[cnt]);

        return dt;
    }

    private string ExtractAttributeGuids()
    {
        StringBuilder attributelist = new StringBuilder();
        foreach (ListItem prop in lstAttribute.Items)
        {
            if (prop.Selected == true)
                attributelist.Append(prop.Value + ",");
        }
        return attributelist.ToString();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            try
            {
                ApplicationCDE appData = LoadAppDatafromForm();
                string attributes = ExtractAttributeGuids();
                string strContactXML = ParseContactsXML();

                string strAppID = ApplicationsBL.InsertApplication(appData, attributes, strContactXML);

                Session["finishAdd"] = "true";
                Response.Redirect("~/Application/ApplicationDataEntry.aspx");
            }
            catch (Exception ex)
            {
                string strErrorType = ex.Message.ToString().Substring(0, 8);

                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                if (strErrorType != "APMError")
                {
                    Server.ClearError();
                    Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                }
            }
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            // Loop through all validation controls to see which
            // generated the errors.
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    protected void lbnew_Click(object sender, EventArgs e)
    {
        Session["search"] = null;
        Response.Redirect("~/Application/ApplicationDataEntry.aspx");
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        string status = ViewState["view"].ToString();
        //ADD NEW APPLICATION
        if (status == "new")
        {
            Response.Redirect("~/Application/ApplicationDataEntry.aspx");
        }
        //EDIT NEW APPLICATION
        else
        {
            if (Request.QueryString["ID"] == null)
            {
                pnlApplication.Visible = false;
                pnlSearch.Visible = true;
            }
            else
            {
                int id = Int32.Parse(Request.QueryString["id"]);
                Response.Redirect("~/Application/ApplicationDataEntryView.aspx?id=" + id);
            }
        }
    }

    public ApplicationCDE LoadAppDatafromForm()
    {
        ApplicationCDE appData = new ApplicationCDE();
        appData.ApplicationName = txtApplicationName.Text;
        appData.OrgID = Int32.Parse(ddlOrgName.SelectedValue);
        appData.ApplicationVersion = txtVersion.Text;
        appData.Active = true;
        appData.Description = txtDescription.Text;
        appData.StartDate = DateTime.Parse(txtStartDate.Text).ToString();
        appData.CompletionDate = DateTime.Parse(txtCompletionDate.Text).ToString();
        if (ViewState["view"].ToString() == "edit")
        {
            appData.ActualCompletedDate = txtActualCompletedDate.Text;
        }
        appData.CreatedBy = Session["loginname"].ToString();
        appData.Active = true;
        appData.ApplicationID = Int32.Parse(appID.Value);
        return appData;
    }

    protected void btnCopy_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Response.Redirect("~/Application/ApplicationDataEntry.aspx?action=add&id=" + txtApplicationID.Text);
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    private string LookupAlias(string strAlias, string strProperty)
    {
        string strUserName;
        string strDomain;
        string[] aryAuthUser = new string[2];
        string strReturn;

        if (!string.IsNullOrEmpty(strAlias))
        {
            strUserName = User.Identity.Name;
            strUserName = strUserName.ToLower();

            char[] strSeperator = new char[] { '\\' };

            aryAuthUser = strUserName.Split(strSeperator);
            strDomain = aryAuthUser[0];
            strUserName = aryAuthUser[1];

            string LDAPConnectionPath = "";
            LDAPConnectionPath = "LDAP://" + strDomain.ToLower();
            try
            {
                DirectoryEntry ent = new DirectoryEntry(LDAPConnectionPath);
                DirectorySearcher search = new DirectorySearcher(ent);
                search.Filter = "(&(objectClass=user)(sAMAccountName=" + strAlias + "))";
                search.PropertiesToLoad.Add(strProperty);
                SearchResult results = search.FindOne();
                if (results != null)
                {
                    strReturn = "";
                    ResultPropertyCollection ResultPropColl;
                    ResultPropColl = results.Properties;
                    foreach (Object myCollection in ResultPropColl[strProperty])
                    {
                        strReturn = myCollection.ToString();
                    }
                }
                else
                {
                    strReturn = "";
                }
                ent.Dispose();
                search.Dispose();

            }
            catch
            {
                strReturn = "";
            }
        }
        else
        {
            strReturn = "";
        }
        if (strReturn.Length > 99 && strProperty == "cn")
            strReturn = strReturn.Substring(0, 100);
        return strReturn;
    }

    private void FillAppInfo(int appID, bool isCopy)
    {
        try
        {
            ApplicationCDE appData = ApplicationsBL.GetApplicationDataByID(appID);

            //Application Metadata
            txtAppID.Text = appID.ToString();
            txtApplicationName.Text = appData.ApplicationName;
            ddlOrgName.SelectedValue = appData.OrgID.ToString();
            txtVersion.Text = appData.ApplicationVersion;
            txtDescription.Text = appData.Description;
            txtStartDate.Text = DateTime.Parse(appData.StartDate.ToString()).ToShortDateString();
            txtCompletionDate.Text = DateTime.Parse(appData.CompletionDate.ToString()).ToShortDateString();
            if (!isCopy)
            {
                if (!string.IsNullOrEmpty(appData.ActualCompletedDate))
                {
                    txtActualCompletedDate.Text = DateTime.Parse(appData.ActualCompletedDate.ToString()).ToShortDateString();
                }
                lblAppOwnerText.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ContactAlias);
            }
            else
            {
                lblAppOwnerText.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(Session["loginname"].ToString());
            }

            //Application Properties
            List<PropertyCDE> propList = ApplicationsBL.GetSelectedAttributesforApplication(appID);
            ViewState["propertylist"] = propList;

            // Fixed by Vineet Batta
            ListItem lItemTemp = null;
            // This is to select the attribute which have already been selected.
            if (propList.Count > 0)
            {
                foreach (PropertyCDE lItem in propList)
                {
                    lItemTemp = new ListItem();
                    lItemTemp.Text = lItem.AttributeName;
                    lItemTemp.Value = lItem.AttributeID;

                    if (lstAttribute.Items.Contains(lItemTemp))
                        lstAttribute.Items.FindByValue(lItemTemp.Value).Selected = true;

                    lItemTemp = null;
                }
            }
            //////////////////////////////
            //Application Contacts
            List<ApplicationContactCDE> contactList = ApplicationsBL.GetContactsByAppID(appData.ApplicationID);
            ViewState["contactlist"] = contactList;
            gridApplicationContact.DataSource = contactList;
            if (contactList.Count > 0)
                gridApplicationContact.PageIndex = 0;
            gridApplicationContact.DataBind();
        }
        catch (Exception ex)
        {
            if (ViewState["view"].ToString() == "edit")
            {
                Response.Redirect("~/Application/ApplicationDataEntry.aspx");
            }
            else
            {
                string strErrorType = ex.Message.ToString().Substring(0, 8);

                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                if (!Request.IsLocal && strErrorType != "APMError")
                {
                    Server.ClearError();
                    Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                }
            }
        }
    }

    protected void gridAppContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        List<ApplicationContactCDE> list = (List<ApplicationContactCDE>)ViewState["contactlist"];
        list.RemoveAt(e.RowIndex + (gridApplicationContact.PageIndex * gridApplicationContact.PageSize));
        ViewState["contactlist"] = list;
        pnlContactError.Visible = false;
        gridApplicationContact.DataSource = list;
        gridApplicationContact.DataBind();
    }

    protected void gridAppContact_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        List<ApplicationContactCDE> list = (List<ApplicationContactCDE>)ViewState["contactlist"];
        gridApplicationContact.PageIndex = e.NewPageIndex;
        ViewState["contactlist"] = list;
        gridApplicationContact.DataSource = list;
        gridApplicationContact.DataBind();
    }

    protected void gridAppContact_RowEditing(object sender, GridViewEditEventArgs e)
    {
        List<ApplicationContactCDE> prevList = (List<ApplicationContactCDE>)ViewState["contactlist"];
        gridApplicationContact.EditIndex = e.NewEditIndex;
        ViewState["contactlist"] = prevList;
        gridApplicationContact.DataSource = prevList;
        gridApplicationContact.DataBind();

        DropDownList ddl = (DropDownList)gridApplicationContact.Rows[e.NewEditIndex].FindControl("ddlEditContactType");
        List<ContactTypeCDE> list = ContactTypesBL.GetEnabledContactTypes("ASC");

        string key = gridApplicationContact.DataKeys[e.NewEditIndex].Value.ToString();
        foreach (ContactTypeCDE cTemp in list)
        {
            ListItem item = new ListItem();
            item.Text = cTemp.ContactType;
            item.Value = cTemp.ContactTypeID;
            if (key == cTemp.ContactTypeID)
                item.Selected = true;
            if (item.Value != "99998b54-da83-4d1a-858c-43a377b86c9e")
                ddl.Items.Add(item);
        }
        ddl.DataBind();
    }

    protected void gridAppContact_RowCancel(object sender, GridViewCancelEditEventArgs e)
    {
        List<ApplicationContactCDE> list = (List<ApplicationContactCDE>)ViewState["contactlist"];
        gridApplicationContact.EditIndex = -1;
        ViewState["contactlist"] = list;
        gridApplicationContact.DataSource = list;
        gridApplicationContact.DataBind();
    }

    protected void gridAppContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        List<ApplicationContactCDE> list = (List<ApplicationContactCDE>)ViewState["contactlist"];
        TextBox txtAlias = (TextBox)gridApplicationContact.Rows[gridApplicationContact.EditIndex].FindControl("txtEditAlias");
        DropDownList ddl = (DropDownList)gridApplicationContact.Rows[gridApplicationContact.EditIndex].FindControl("ddlEditContactType");
        TextBox txtName = (TextBox)gridApplicationContact.Rows[gridApplicationContact.EditIndex].FindControl("txtEditName");
        TextBox txtEmail = (TextBox)gridApplicationContact.Rows[gridApplicationContact.EditIndex].FindControl("txtEditEmail");

        int i = 0;
        int currentRow = (e.RowIndex + (gridApplicationContact.PageIndex * gridApplicationContact.PageSize));

        foreach (ApplicationContactCDE c1 in list)
        {
            if (txtAlias.Text == c1.Alias && ddl.SelectedItem.Value == c1.ContactTypeID && currentRow != i)
            {
                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "An Application Contact with the same Alias and Contact Type already exists.", "errorkey");
                return;
            }
            i++;
        }

        ApplicationContactCDE contact = new ApplicationContactCDE();
        contact.Alias = txtAlias.Text;
        contact.Name = txtName.Text;
        contact.Email = txtEmail.Text;
        contact.Active = true;
        contact.ContactTypeID = ddl.SelectedItem.Value;
        contact.ContactTypeName = ddl.SelectedItem.Text;

        list.RemoveAt(currentRow);
        list.Insert(currentRow, contact);

        pnlContactError.Visible = false;

        gridApplicationContact.EditIndex = -1;
        ViewState["contactlist"] = list;
        gridApplicationContact.DataSource = list;
        gridApplicationContact.DataBind();
    }

    protected void btnFindUser_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string strAlias = txtInsertAlias.Text;
            string name = LookupAlias(strAlias, "cn");
            string email = LookupAlias(strAlias, "mail");

            if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(email))
            {
                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "No user was found", "updateuser");
            }
            else
            {
                txtInsertEmail.Text = email;
                txtInsertName.Text = name;
            }
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {

            ApplicationContactCDE contact = new ApplicationContactCDE();
            contact.Alias = txtInsertAlias.Text;
            contact.ContactTypeID = ddlInsertContactType.SelectedValue;
            contact.Name = txtInsertName.Text;
            contact.Email = txtInsertEmail.Text;
            contact.ContactTypeName = ddlInsertContactType.Items[ddlInsertContactType.SelectedIndex].Text;
            contact.Active = true;

            List<ApplicationContactCDE> contactList = (List<ApplicationContactCDE>)ViewState["contactlist"];
            foreach (ApplicationContactCDE c1 in contactList)
            {
                if (contact.Alias == c1.Alias && contact.ContactTypeID == c1.ContactTypeID)
                {
                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "An Application Contact with the same alias already exists.", "errorkey");
                    return;
                }
            }

            contactList.Add(contact);
            ViewState["contactlist"] = contactList;
            gridApplicationContact.DataSource = contactList;
            gridApplicationContact.DataBind();

            txtInsertAlias.Text = null;
            ddlInsertContactType.SelectedIndex = -1;
            txtInsertName.Text = null;
            txtInsertEmail.Text = null;
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    private void SetEditApplicationActive()
    {
        pnlApplication.Visible = false;
        pnlSearch.Visible = true;

        btnGo.Visible = false;
        lstApplicationNames.Visible = false;
        lblResult.Visible = false;
        rdsearchType.SelectedValue = "0";
        txtSearch.Text = null;
    }

    protected void btnInsertProperty_Click(object sender, EventArgs e)
    {
        SetTabActive(ViewState["view"].ToString());

        PropertyCDE prop = new PropertyCDE();
        prop.Active = true;

        List<PropertyCDE> list = (List<PropertyCDE>)ViewState["propertylist"];
        foreach (PropertyCDE temp in list)
        {
            if (temp.AttributeID == prop.AttributeID)
            {
                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "The selected Application Property already exists.", "errorkey");
                return;
            }
        }

        list.Add(prop);
        ViewState["propertylist"] = list;
    }

    private void LoadOrganizationDDL()
    {
        DataSet ds = WTRIAssessmentBL.dsLoadDataSet("SPM_spGetFlatOrgList");
        ddlOrgName.DataSource = ds;
        ddlOrgName.DataBind();
        ds.Dispose();
    }

    private void LoadContactTypeDDL()
    {
        List<ContactTypeCDE> list = ContactTypesBL.GetEnabledContactTypes("ASC");
        foreach (ContactTypeCDE contact in list)
        {
            ListItem item = new ListItem();
            item.Text = contact.ContactType;
            item.Value = contact.ContactTypeID;
            if (item.Value != "99998b54-da83-4d1a-858c-43a377b86c9e")
            {
                ddlInsertContactType.Items.Add(item);
            }
        }
    }

    private void LoadPropertyDDL()
    {
        List<PropertyCDE> list = AttributesBL.GetEnableAttributes("ASC");
        foreach (PropertyCDE prop in list)
        {
            ListItem item = new ListItem();
            item.Text = prop.AttributeName;
            item.Value = prop.AttributeID;
        }
    }

    /// <summary>
    /// This method will load the attributes in the system to be displayed in multi-select list box.
    /// </summary>
    private void LoadPropertyListBox()
    {
        List<PropertyCDE> list = AttributesBL.GetEnableAttributes("ASC");
        foreach (PropertyCDE prop in list)
        {
            ListItem item = new ListItem();
            item.Text = prop.AttributeName;
            item.Value = prop.AttributeID;
            lstAttribute.Items.Add(item);
        }
    }

    protected void gridAppContact_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (System.Web.UI.Control BaseControl in e.Row.Cells[0].Controls)
            {
                if (BaseControl.GetType().BaseType == typeof(LinkButton))
                {
                    LinkButton linkBtn = (LinkButton)BaseControl;
                    if (linkBtn.CommandName == "Delete")
                        linkBtn.OnClientClick = "return confirm('Are you sure you want to remove this Application Contact?');";
                }
            }

            ApplicationContactCDE contact = (ApplicationContactCDE)e.Row.DataItem;
            if (!contact.Active)
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
                e.Row.Cells[2].ForeColor = System.Drawing.Color.Red;
                e.Row.Cells[3].ForeColor = System.Drawing.Color.Red;
                e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;

                Label cType = (Label)e.Row.FindControl("lblContactType");
                if (cType != null)
                {
                    cType.Text = contact.ContactTypeName + " (Inactive)";
                }

                pnlContactError.Visible = true;
            }
        }
    }

    private void SetTabActive(string tab)
    {
        if (tab == "new")
            SetNew();
        else
            SetEdit();
    }

    protected void gvProperty_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (System.Web.UI.Control BaseControl in e.Row.Cells[0].Controls)
            {
                if (BaseControl.GetType().BaseType == typeof(LinkButton))
                {
                    LinkButton linkBtn = (LinkButton)BaseControl;
                    if (linkBtn.CommandName == "Delete")
                        linkBtn.OnClientClick = "return confirm('Are you sure you want to remove this Application Property?');";
                }

                PropertyCDE item = (PropertyCDE)e.Row.DataItem;
                if (!item.Active)
                {
                    e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
                    Label lblProperty = (Label)e.Row.FindControl("lblGProperty");
                    lblProperty.Text = item.AttributeName + " (Inactive)";
                }
            }
        }
    }

    private void SetAddApplicationActive()
    {
        pnlApplication.Visible = true;
        pnlError.Visible = false;
        pnlCopy.Visible = true;
        pnlApplicationID.Visible = false;
        pnlCompletedDate.Visible = false;
        pnlAppPropertyAdd.Visible = true;
        pnlAppContactAdd.Visible = true;
        pnlContactError.Visible = false;
        pnlSearch.Visible = false;

        btnSubmit.Visible = true;
        btnUpdate.Visible = false;
        btnReset.Visible = true;
        btnReset.Text = "Reset";

        if (ddlInsertContactType.Items.Count == 1)
            btnAdd.Enabled = false;
        else
            btnAdd.Enabled = true;

        txtApplicationID.Text = null;
        txtApplicationName.Text = null;
        ddlOrgName.SelectedIndex = -1;
        txtVersion.Text = null;
        txtDescription.Text = null;
        txtStartDate.Text = null;
        txtCompletionDate.Text = null;
        txtActualCompletedDate.Text = null;

        txtInsertAlias.Text = null;
        ddlInsertContactType.SelectedIndex = -1;
        txtInsertEmail.Text = null;
        txtInsertName.Text = null;

        lblAppOwnerText.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(Session["loginname"].ToString());

        List<ApplicationContactCDE> list = new List<ApplicationContactCDE>();
        ViewState["contactlist"] = list;
        gridApplicationContact.DataSource = list;
        gridApplicationContact.DataBind();

        List<PropertyCDE> propList = new List<PropertyCDE>();
        ViewState["propertylist"] = propList;
    }
}